package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.domain.Dish;
import com.example.reggie.domain.DishFlavor;
import com.example.reggie.dto.DishDto;
import com.example.reggie.service.DishFlavorService;
import com.example.reggie.service.DishService;
import com.example.reggie.dao.DishDao;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 23333
 * @description 针对表【dish(菜品管理)】的数据库操作Service实现
 * @createDate 2023-06-06 10:35:35
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时保存对应的口味数据
     *
     * @param dishDto
     */
    @Transactional
    @Override
    public void saveDishWithDishFlavors(DishDto dishDto) {
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        long dishId = dishDto.getId();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 查询菜品和对应的口味数据
     *
     * @param id
     * @return
     */
    @Override
    public DishDto selectDishWithFlavorsById(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lqw);
        dishDto.setFlavors(dishFlavorList);
        return dishDto;
    }

    /**
     * 更新菜品信息和口味数据
     *
     * @param dishDto
     */
    @Transactional
    @Override
    public void updateDishInfo(DishDto dishDto) {
        this.updateById(dishDto);
        List<DishFlavor> flavorList = dishDto.getFlavors();

        Long dishId = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishId);
        dishFlavorService.remove(lqw);

        for (DishFlavor flavor : flavorList) {
            flavor.setId(null);
            flavor.setDishId(dishId);
            dishFlavorService.save(flavor);
        }
    }
}




